package com.yunhai.device.config;

import com.yunhai.common.utils.JwtUtils;
import com.yunhai.device.service.UserRedisService;
import com.yunhai.model.entity.ums.UmsUser;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserRedisService userRedisService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("request.getRequestURI(): "+request.getRequestURI());

        //1、从请求头中获取 token
        String token = request.getHeader("token");
        if( !StringUtils.hasText(token) || "/auth/username".equals(request.getRequestURI())){

            //如果 token 不存在，则直接放行，由后面的拦截器进行拦截。
            filterChain.doFilter(request, response);
            return;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            String payload = claims.getSubject();
            UmsUser user = userRedisService.getUser(payload);
            //用户信息不存在即表示过期了。
            if( user == null ){
                filterChain.doFilter(request, response);
                return;
            }

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
            //这个就是告诉 spring security 用户已经登录。
            SecurityContextHolder.getContext().setAuthentication(authentication);

            //放行
            filterChain.doFilter(request, response);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
